package com.qsl.juc.producer_consumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock 实现生产者与消费者
 *
 * @author 青石路
 * @date 2021/3/15 21:37
 */
public class LockDemo {

    public static void main(String[] args) {
        ShareInfo shareInfo = new ShareInfo();

        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                shareInfo.increment();
            }
        }, "t1").start();

        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                shareInfo.decrement();
            }
        }, "t2").start();

/*        new Thread(() -> {
            for (int i=1; i<=5; i++) {
                shareInfo.increment();
            }
        }, "t3").start();

        new Thread(() -> {
            for (int i=1; i<=5; i++) {
                shareInfo.decrement();
            }
        }, "t4").start();*/
    }

    static class ShareInfo {
        private int num = 0;
        private Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        public void increment() {

            lock.lock();
            try {

                // 防止虚假唤醒，用 while 而不是 if；用 > 2 的线程数去测试
                while (num != 0) {
                    condition.await();
                }
                num++;
                System.out.println(Thread.currentThread().getName() + " " + num);
                condition.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void decrement() {
            lock.lock();
            try {

                // 防止虚假唤醒，用 while 而不是 if；用 > 2 的线程数去测试
                while (num == 0) {
                    condition.await();
                }
                num--;
                System.out.println(Thread.currentThread().getName() + " " + num);
                condition.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
